<!-- 巡更管理-添加巡更计划 -->
<template>
  <div>
    <el-dialog :visible="dialogVisible" :before-close="handleCloseBindWarnStandard" :close-on-click-modal="false" :title="title" width="500px" height="300px">
      <el-form v-loading="formLoading" ref="dialogForm" :model="dialogForm" :rules="rules" label-width="120px">
        <el-form-item label="所属单位" prop="corp_id">
          <el-select v-model="dialogForm.corp_id" clearable filterable allow-create default-first-option autocomplete="off" placeholder="请选择单位名称" @change="companyChange">
            <el-option v-for="item in companyList" :key="item.corp_id" :label="item.name" :value="item.corp_id" />
          </el-select>
          <!-- <el-input v-model="dialogForm.corp_name" class="el-disabled" readonly="readonly"/> -->
        </el-form-item>
        <el-form-item label="所属建筑群" prop="park_id" >
          <el-select v-model="dialogForm.park_id" placeholder="请选择所属建筑群">
            <el-option v-for="item in parksList" :key="item.park_id" :label="item.name" :value="item.park_id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="计划名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入计划名称" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-select v-model="dialogForm.leader" placeholder="请选择负责人">
            <el-option v-for="item in userLeaderList" :key="item.uuid" :label="item.nickname" :value="item.uuid" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_at">
          <el-date-picker
            v-model="dialogForm.start_at"
            :picker-options="pickerOptions0"
            format="yyyy年MM月dd日"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="请选择开始时间"/>
        </el-form-item>
        <el-form-item label="任务执行人" prop="workers">
          <el-select v-model="dialogForm.workers" placeholder="请选择任务执行人" multiple>
            <el-option v-for="item in userWorkerList" :key="item.uuid" :label="item.nickname" :value="item.uuid" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="nextDialog">下一步</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleOther" :before-close="handleCloseBindWarnStandard" :title="title" width="900px" height="400px">
      <el-form ref="dialogForm1" :model="dialogForm1" :rules="rules1" label-width="120px">
        <el-form-item label="频次" prop="frequency">
          <el-input v-model="dialogForm1.frequency" style="width: 240px;" placeholder="请输入频次" @change="changeFrequency">
            <template slot="append">次/天</template>
          </el-input>
        </el-form-item>
        <el-form-item label="任务时间" prop="plan_list">
          <ul class="plan-list">
            <li v-for="(item, index) in dialogForm1.plan_list" :key="index">
              <el-form-item :label="item.label" prop="begin_time">
                <el-time-select
                  v-model="item.begin_time"
                  :picker-options="{
                    step: '00:01',
                    start: '00:00',
                    end: '23:59',
                    minTime: item.minTime
                  }"
                  format="HH:mm"
                  value-format="HH:mm"
                  style="width: 150px;"
                  placeholder="请选择时间点"/>
              </el-form-item>
              <el-form-item label="任务时长" prop="patrol_begin_date">
                <el-input v-model="item.hour" placeholder="请输入" style="width: 144px;" @change="initNumber(index)">
                  <template slot="append">小时</template>
                </el-input>
                <el-input v-model="item.minute" placeholder="请输入" style="width: 144px;" @change="initNumber(index)">
                  <template slot="append">分钟</template>
                </el-input>
              </el-form-item>
            </li>
          </ul>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="nextDialog1">下一步</el-button>
        <el-button @click="prevDialog1">上一步</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisibleMap" :before-close="handleCloseBindWarnStandard" :title="title" width="700px" height="400px">
      <el-form ref="dialogForm2" :model="dialogForm2" :rules="rules2" label-width="120px">
        <el-form-item label="巡更点" prop="points">
          <el-transfer v-model="dialogForm2.patrolPoint" :data="pointPositionList" :titles="['巡更点', '选中的巡更点']">
            <span slot-scope="{ option }">{{ option.label }}</span>
          </el-transfer>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="prevDialog2">上一步</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getSocialUnit } from '@/api/company'
import { parksList } from '@/api/park'
import { userLeaderList, userWorkerList } from '@/api/common'
import { pointPositionList } from '@/api/pointPosition'
import { patrolPlansAdd, patrolPlansUpdate } from '@/api/patrolPlans'
export default {
  props: {
    dialogForm: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogForm1: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogForm2: {
      type: Object,
      default: () => {
        return {}
      }
    },
    dialogType: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data() {
    return {
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      dialogVisible: true,
      // 巡更点
      dialogVisibleMap: false,
      // 频次
      dialogVisibleOther: false,
      title: '',
      requestFn: {},
      data: [],
      plan_list: [],
      companyList: [],
      addType: '单个添加',
      // 添加form验证
      rules: {
        corp_id: [{
          required: true,
          message: '请输入所属单位名称',
          trigger: 'change'
        }],
        park_id: [{
          required: true,
          message: '请选择所属建筑群',
          trigger: 'change'
        }],
        name: [{
          required: true,
          message: '请输入计划名称',
          trigger: 'change'
        }],
        leader: [{
          required: true,
          message: '请输入负责人',
          trigger: 'change'
        }],
        start_at: [{
          required: true,
          message: '请选择开始时间',
          trigger: 'change'
        }],
        workers: [{
          required: true,
          message: '请选择任务执行人',
          trigger: 'blur'
        }]
      },
      rules1: {
        frequency: [{
          required: true,
          message: '请输入频次',
          trigger: 'change'
        }],
        plan_list: [{
          required: true,
          message: '请输入任务时间',
          trigger: 'change'
        }]
      },
      rules2: {
        patrolPoint: [{
          required: true,
          message: '请选择巡更点',
          trigger: 'change'
        }]
      },
      parksList: [],
      userLeaderList: [],
      userWorkerList: [],
      pointPositionList: [],
      formLoading: false
    }
  },
  watch: {
    'dialogForm1.plan_list': {
      handler: function(val) {
        val.forEach((item, index) => {
          if (index !== (this.dialogForm1.plan_list.length - 1) && item.hour !== '' && item.minute !== '' && item.begin_time !== '') {
            var minTime = (parseInt(item.begin_time.split(':')[0]) + parseInt(item.hour)) + ':' + (parseInt(item.begin_time.split(':')[1]) + parseInt(item.minute) - 1)
            // var hStr = (parseInt(item.begin_time.split(':')[0]) + parseInt(item.hour))
            // var mStr = (parseInt(item.begin_time.split(':')[1]) + parseInt(item.minute) + 1)
            // if (mStr > 59) {
            //   hStr = hStr + 1
            //   mStr = '00'
            // }
            this.dialogForm1.plan_list[(index + 1)].minTime = minTime
            // this.dialogForm1.plan_list[(index + 1)].begin_time = hStr + ':' + mStr
          }
          item.hour = item.hour.replace(/[^0-9]/ig, '')
          item.minute = item.minute.replace(/[^0-9]/ig, '')
        })
      },
      deep: true
    },
    dialogType(val) {
      console.log(val)
      if (val === '添加') {
        this.title = '添加计划'
      }
      if (val === '修改') {
        this.title = '修改计划'
      }
    }
  },
  created() {
    this.init(this.dialogType)
    this.getSocialUnit()
  },
  methods: {
    initNumber(data) {
      console.log(data)
      this.dialogForm1.plan_list.forEach((item, index) => {
        if (index > data) {
          console.log(index)
          this.dialogForm1.plan_list[index].begin_time = ''
        }
      })
    },
    init(dialogType) {
      if (this.dialogType === '添加') {
        this.title = '添加计划'
        this.requestFn = patrolPlansAdd
      }
      if (this.dialogType === '修改') {
        this.title = '修改计划'
        this.requestFn = patrolPlansUpdate
        this.getSocialUnit()
        this.getParksList()
        this.getserLeaderList()
        this.getUserWorkerList()
        this.getPointPositionList()
      }
    },
    submitForm(val) {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const that = this
          that.formLoading = true
          var params = {
            ...that.dialogForm
          }
          params.points = that.dialogForm2.patrolPoint.join(',')
          params.cycle_content = []
          console.log(JSON.stringify(that.dialogForm1.plan_list))
          for (var i = 0; i < that.dialogForm1.plan_list.length; i++) {
            params.cycle_content.push({
              start: that.dialogForm1.plan_list[i].begin_time,
              interval_hour: that.dialogForm1.plan_list[i].hour,
              interval_min: that.dialogForm1.plan_list[i].minute
            })
          }
          params.frequency = parseInt(that.dialogForm1.frequency)
          params.cycle_content = JSON.stringify(params.cycle_content)
          params.workers = params.workers.join(',')
          if (that.dialogType === '修改') {
            params.leader_id = that.dialogForm.leader
            params.worker_ids = params.workers
            params.is_forbidden = that.dialogForm.is_forbidden ? '2' : '1'
            delete params['imgUrl']
          }
          that.requestFn(params)
            .then((res) => {
              const data = res.data
              if (data.code === 40000) {
                that.$message.success(data.message)
                that.$emit('submitForm', that.dialogForm)
                that.formLoading = false
              } else {
                that.$message.warning(data.message)
                that.formLoading = false
              }
            })
            .catch((err) => {
              console.log(err)
              that.formLoading = false
            })
        }
      })
    },
    // 关闭弹窗
    handleCancel() {
      this.$refs['dialogForm'].resetFields()
      this.$emit('getCancel')
      this.dialogVisible = true
    },
    // 关闭弹窗，不可以删这个方法。不用这个方法点击遮罩层关闭会报错
    handleCloseBindWarnStandard() {
      this.$refs['dialogForm'].resetFields()
      this.$emit('closeBindWarnStandard')
      this.dialogVisible = true
    },
    // 第一个弹窗下一步
    nextDialog() {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          this.dialogVisibleOther = true
          this.dialogVisible = false
          console.log(JSON.stringify(this.dialogForm1))
        }
      })
    },
    // 第二个弹窗上一步
    prevDialog1() {
      this.dialogVisibleOther = false
      this.dialogVisible = true
    },
    // 第二个弹窗下一步
    nextDialog1() {
      this.$refs['dialogForm1'].validate((valid) => {
        if (valid) {
          console.log(this.dialogForm1)
          let flag = true
          this.dialogForm1.plan_list.forEach((item, index) => {
            if (item.begin_time === '' || item.hour === '' || item.minute === '') {
              flag = false
            }
          })
          if (flag) {
            this.dialogVisibleMap = true
            this.dialogVisibleOther = false
          } else {
            this.$message.warning('请填写信息！')
          }
        }
      })
    },
    // 第三个弹窗上一步
    prevDialog2() {
      this.dialogVisibleOther = true
      this.dialogVisibleMap = false
    },
    // 获取建筑群列表
    getParksList() {
      const that = this
      var listQuery = {
        page: 1,
        offset: 1000,
        corp_id: that.dialogForm.corp_id
      }
      parksList(listQuery)
        .then(response => {
          if (response.data.code === 40000) {
            that.parksList = []
            response.data.data.data.forEach(function(value, index, array) {
              array[index].index = index
              that.parksList.push(array[index])
            })
          }
        })
        .catch(() => {
          this.parksList = []
        })
    },
    // 获取负责人
    getserLeaderList() {
      const that = this
      var listQuery = {
        page: 1,
        offset: 1000,
        corp_id: that.dialogForm.corp_id
      }
      userLeaderList(listQuery)
        .then(response => {
          if (response.data.code === 40000) {
            that.userLeaderList = []
            response.data.data.forEach(function(value, index, array) {
              array[index].index = index
              that.userLeaderList.push(array[index])
            })
          }
        })
        .catch(() => {
          this.userLeaderList = []
        })
    },
    // 获取执行人
    getUserWorkerList() {
      const that = this
      var listQuery = {
        page: 1,
        offset: 1000,
        corp_id: that.dialogForm.corp_id
      }
      userWorkerList(listQuery)
        .then(response => {
          if (response.data.code === 40000) {
            that.userWorkerList = []
            response.data.data.forEach(function(value, index, array) {
              array[index].index = index
              that.userWorkerList.push(array[index])
            })
          }
        })
        .catch(() => {
          this.userWorkerList = []
        })
    },
    // 获取巡更点
    getPointPositionList() {
      const that = this
      var listQuery = {
        page: 1,
        offset: 1000,
        corp_id: that.dialogForm.corp_id
      }
      pointPositionList(listQuery)
        .then(response => {
          if (response.data.code === 40000) {
            that.pointPositionList = []
            response.data.data.data.forEach(function(value, index, array) {
              array[index].index = index
              that.pointPositionList.push({
                'key': array[index].point_id,
                'label': array[index].name
              })
            })
          }
        })
        .catch(() => {
          this.pointPositionList = []
        })
    },
    // 获取单位下拉框
    getSocialUnit() {
      const that = this
      getSocialUnit()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            if (data.data && data.data.length > 0) {
              that.companyList = data.data
            }
          } else {
            that.$message.warning(response.data.message)
          }
        })
        .catch(() => {
        })
    },
    companyChange(value) {
      this.dialogForm.corp_id = value
      this.getParksList()
      this.getserLeaderList()
      this.getUserWorkerList()
      this.getPointPositionList()
      this.dialogForm.leader = ''
      this.dialogForm.park_id = ''
      this.dialogForm.workers = ''
      this.dialogForm2.patrolPoint = []
    },
    // 增加任务时间
    changeFrequency(data) {
      if (isNaN(parseInt(data))) {
        this.dialogForm1.frequency = 0
      } else {
        if (this.dialogType === '修改') {
          var count = parseInt(data) - parseInt(this.dialogForm1.plan_list.length)
          this.dialogForm1.plan_list = this.dialogForm1.plan_list === '' ? [] : this.dialogForm1.plan_list
          for (var i = 0; i < count; i++) {
            this.dialogForm1.plan_list.push({
              label: '开始时间',
              begin_time: '',
              hour: '',
              minute: '',
              minTime: ''
            })
          }
        } else {
          this.dialogForm1.plan_list = []
          for (var k = 0; k < parseInt(data); k++) {
            this.dialogForm1.plan_list.push({
              label: '开始时间',
              begin_time: '',
              hour: '',
              minute: '',
              minTime: ''
            })
          }
        }
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.plan-list{
  overflow: hidden;
  margin-top: 36px;
  li{
    width: 100%;
    margin-bottom:10px;
    .el-form-item{
      display: inline-block;
    }
  }
}
</style>
